package inits

import (
	"fmt"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"hxzkx/global/model"
	"time"
)

func Init(path string) {
	ReadConfig(path)
	MysqlConn()
	MysqlTablesAuth()
	RedisConn()
}

func RedisConn() {
	model.RDB = redis.NewClient(&redis.Options{
		Addr:     model.Conf.Redis.Addr,
		Password: model.Conf.Redis.Password,
	})
	if err := model.RDB.Ping(model.Ctx).Err(); err != nil {
		fmt.Println(err)
	}
	fmt.Println("redis connect success")
}

func MysqlTablesAuth() {
	err := model.DB.AutoMigrate(&model.PaymentOrder{}, &model.PaymentRecord{}, &model.PaymentMethod{}, &model.Order{}, &model.Passenger{})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("tables auth success")
}

func MysqlConn() {
	open, err := gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", model.Conf.Mysql.User, model.Conf.Mysql.Password, model.Conf.Mysql.Addr, model.Conf.Mysql.Database)))
	if err != nil {
		panic(err)
	}
	db, err := open.DB()
	if err != nil {
		panic(err)
	}
	db.SetConnMaxLifetime(time.Minute * 5)
	db.SetMaxOpenConns(30)
	db.SetMaxIdleConns(20)
	model.DB = open
	fmt.Println("mysql connect success")
}

func ReadConfig(path string) {
	paths := fmt.Sprintf("../../conf/%s.yaml", path)
	viper.SetConfigFile(paths)
	viper.ReadInConfig()
	viper.Unmarshal(&model.Conf)
	fmt.Println(model.Conf)
}
